<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta name="baidu-site-verification" content="sc1B5Cxcoz">
  <meta name="google-site-verification" content="OLcRj7lMnauxKrhFT3Q8Nvcexgv22NvlEmVZShKQKR8">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">


























  

<link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.6.2/css/font-awesome.min.css">

<link rel="stylesheet" href="/css/main.css?v=7.0.1">


  <link rel="apple-touch-icon" sizes="180x180" href="/uploads/apple-touch.png?v=7.0.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/uploads/favicon-32x32.png?v=7.0.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/uploads/favicon-16x16.png?v=7.0.1">








<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.0.1',
    sidebar: {"position":"right","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: false,
    fancybox: false,
    fastclick: false,
    lazyload: true,
    tabs: true,
    motion: {"enable":true,"async":true,"transition":{"post_block":"fadeIn","post_header":"fadeIn","post_body":"fadeIn","coll_header":"fadeIn","sidebar":"fadeIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="前言提起中国的lua产品，就不得不想到skynet，一款针对游戏，但又不仅限于游戏的服务端架构。skynet充分利用了lua的特性，并且在此基础上易扩展HTTP、HTTPS、WebSocket等模块，因此由skynet入手理解lua原理以及服务端架构是一个非常不错的选择。 通过skynet，我们可以构建许多小巧而高性能、高可用的应用。废话不多说，让我们一起来探索skynet架构吧~ skynet通">
<meta name="keywords" content="源码分析,服务端,lua,skynet,lua_State">
<meta property="og:type" content="article">
<meta property="og:title" content="【Lua杂谈】基于lua的服务端架构——skynet通信原理与源码分析">
<meta property="og:url" content="http://utmhikari.github.io/2019/10/20/luatalk/skynet/index.html">
<meta property="og:site_name" content="HiKariのTechLab">
<meta property="og:description" content="前言提起中国的lua产品，就不得不想到skynet，一款针对游戏，但又不仅限于游戏的服务端架构。skynet充分利用了lua的特性，并且在此基础上易扩展HTTP、HTTPS、WebSocket等模块，因此由skynet入手理解lua原理以及服务端架构是一个非常不错的选择。 通过skynet，我们可以构建许多小巧而高性能、高可用的应用。废话不多说，让我们一起来探索skynet架构吧~ skynet通">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-10-19T19:35:14.969Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【Lua杂谈】基于lua的服务端架构——skynet通信原理与源码分析">
<meta name="twitter:description" content="前言提起中国的lua产品，就不得不想到skynet，一款针对游戏，但又不仅限于游戏的服务端架构。skynet充分利用了lua的特性，并且在此基础上易扩展HTTP、HTTPS、WebSocket等模块，因此由skynet入手理解lua原理以及服务端架构是一个非常不错的选择。 通过skynet，我们可以构建许多小巧而高性能、高可用的应用。废话不多说，让我们一起来探索skynet架构吧~ skynet通">






  <link rel="canonical" href="http://utmhikari.github.io/2019/10/20/luatalk/skynet/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>【Lua杂谈】基于lua的服务端架构——skynet通信原理与源码分析 | HiKariのTechLab</title>
  












  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">HiKariのTechLab</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">光の技术屋</h1>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-sitemap">

    
    
    
      
    

    

    <a href="/sitemap.xml" rel="section"><i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br>站点地图</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    
  
  
  
  

  

  <span class="exturl github-corner" data-url="aHR0cHM6Ly9naXRodWIuY29tL3V0bWhpa2FyaQ==" title="关注HiKariのGithub" aria-label="关注HiKariのGithub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill: #222; color: #fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></span>



    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://utmhikari.github.io/2019/10/20/luatalk/skynet/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ひかり.HDQ">
      <meta itemprop="description" content="简约即走心">
      <meta itemprop="image" content="/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="HiKariのTechLab">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">【Lua杂谈】基于lua的服务端架构——skynet通信原理与源码分析

              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-10-20 03:32:12 / 修改时间：03:35:14" itemprop="dateCreated datePublished" datetime="2019-10-20T03:32:12+08:00">2019-10-20</time>
            

            
              

              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Lua杂谈/" itemprop="url" rel="index"><span itemprop="name">Lua杂谈</span></a></span>

                
                
              
            </span>
          

          
            
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon">
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>提起中国的lua产品，就不得不想到<span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2Nsb3Vkd3Uvc2t5bmV0" title="https://github.com/cloudwu/skynet">skynet<i class="fa fa-external-link"></i></span>，一款针对游戏，但又不仅限于游戏的服务端架构。skynet充分利用了lua的特性，并且在此基础上易扩展HTTP、HTTPS、WebSocket等模块，因此由skynet入手理解lua原理以及服务端架构是一个非常不错的选择。</p>
<p>通过skynet，我们可以构建许多小巧而高性能、高可用的应用。废话不多说，让我们一起来探索skynet架构吧~</p>
<h2 id="skynet通信原理与源码分析"><a href="#skynet通信原理与源码分析" class="headerlink" title="skynet通信原理与源码分析"></a>skynet通信原理与源码分析</h2><p>服务端架构中，不同子服务的通信调度是核心功能。因此，我们以单点（standalone）的skynet实例为例，由外而内，逐步剖析。</p>
<p>要介绍skynet的通信原理，首先要提到lua中的一个概念——lua_State。lua_State是lua的运行时（runtime），是一个原生隔离的、高性能的运行环境，若在多核并行运行lua_State，其性能一定不会差。lua作为嵌入式语言，以C为基础，可以实现操作系统粒度级的lua_State调度，因此skynet也就如同lua_State管理器一样了。</p>
<p>每一种业务可以看作一个service，而每一个service中，都会有一个lua_State充当执行业务逻辑的环境。举个例子，在实际开发当中，比如做一个HTTP服务的话，我们需要自己预先配置好的skynet service主入口lua文件中，写上<code>skynet.uniqueservice(&quot;app&quot;)</code>启动一个独特的名为<code>app</code>的服务，而后在其中的逻辑中，根据每一个HTTP连接，解析其中的数据包。并调用<code>skynet.newservice</code>动态创建单独的上下文服务<code>ctx</code>来处理这个请求。<code>ctx</code>服务还有可能需要查询数据库中的数据，并返回结果，因此我们可能还需要通过<code>skynet.uniqueservice(&quot;db&quot;)</code>预先创建数据库服务<code>db</code>二次封装skynet内置mongo、mysql库的功能，然后再通过<code>skynet.call</code>来与<code>db</code>服务通信，获得<code>db</code>服务某个函数执行的返回结果，再在<code>ctx</code>服务的处理逻辑中写入HTTP Response，从而完成整个处理过程。在这一过程中，具体业务逻辑的处理都会在各个service所拥有的lua_State中运行，但调度通信的逻辑，则就是底层的活了。</p>
<p>因此在skynet底层中，不仅需要支持多个lua_State的运转，而且相对更有挑战性的是，如何让service之间能够相互交流。为了解决这个问题，我们可以看到，在底层中，每一个service都属于<code>snlua</code>类型。<code>snlua</code>除了包括自己的lua_State之外，还维护了一个称之为context的运行状态：</p>
<a id="more"></a>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// lua-skynet.c</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">snlua</span> &#123;</span></span><br><span class="line">    lua_State * L;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">skynet_context</span> * <span class="title">ctx</span>;</span></span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">char</span> * preload;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// skynet_server.c</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">skynet_context</span> &#123;</span></span><br><span class="line">    <span class="keyword">void</span> * instance;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">skynet_module</span> * <span class="title">mod</span>;</span></span><br><span class="line">    <span class="keyword">void</span> * cb_ud;</span><br><span class="line">    skynet_cb cb; <span class="comment">// 用于处理每一个消息的回调函数</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">message_queue</span> *<span class="title">queue</span>;</span> <span class="comment">// context专属的message_queue</span></span><br><span class="line">    FILE * logfile;</span><br><span class="line">    <span class="keyword">uint64_t</span> cpu_cost; <span class="comment">// in microsec</span></span><br><span class="line">    <span class="keyword">uint64_t</span> cpu_start; <span class="comment">// in microsec</span></span><br><span class="line">    <span class="keyword">char</span> result[<span class="number">32</span>];</span><br><span class="line">    <span class="keyword">uint32_t</span> handle; <span class="comment">// 维护一个handle，可以理解为操作系统的URL</span></span><br><span class="line">    <span class="keyword">int</span> session_id;</span><br><span class="line">    <span class="keyword">int</span> ref;</span><br><span class="line">    <span class="keyword">int</span> message_count;</span><br><span class="line">    <span class="keyword">bool</span> init;</span><br><span class="line">    <span class="keyword">bool</span> endless;</span><br><span class="line">    <span class="keyword">bool</span> profile;</span><br><span class="line"></span><br><span class="line">    CHECKCALLING_DECL</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>在lua业务逻辑中执行<code>skynet.newservice</code>或<code>skynet.uniqueservice</code>，skynet框架就会根据服务名称读取对应入口的代码执行。要让这个服务启动，入口文件的代码还需要添加<code>skynet.start</code>函数：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- skynet.lua</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">skynet.start</span><span class="params">(start_func)</span></span></span><br><span class="line">    c.callback(skynet.dispatch_message)</span><br><span class="line">    init_thread = skynet.timeout(<span class="number">0</span>, <span class="function"><span class="keyword">function</span><span class="params">()</span></span></span><br><span class="line">        skynet.init_service(start_func)</span><br><span class="line">        init_thread = <span class="literal">nil</span></span><br><span class="line">    <span class="keyword">end</span>)</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>
<p>可以看到在启动之时，会通过<code>c.callback</code>注册一个回调函数用于分发消息，其逻辑如下：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// lua-skynet.c</span></span><br><span class="line"><span class="comment">// 对应c.callback</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">int</span></span><br><span class="line">lcallback(lua_State *L) &#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">skynet_context</span> * <span class="title">context</span> = <span class="title">lua_touserdata</span>(<span class="title">L</span>, <span class="title">lua_upvalueindex</span>(1));</span></span><br><span class="line">    <span class="keyword">int</span> forward = lua_toboolean(L, <span class="number">2</span>);</span><br><span class="line">    luaL_checktype(L,<span class="number">1</span>,LUA_TFUNCTION);</span><br><span class="line">    lua_settop(L,<span class="number">1</span>);</span><br><span class="line">    lua_rawsetp(L, LUA_REGISTRYINDEX, _cb);</span><br><span class="line">    lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_MAINTHREAD);</span><br><span class="line">    lua_State *gL = lua_tothread(L,<span class="number">-1</span>);</span><br><span class="line">    <span class="keyword">if</span> (forward) &#123;</span><br><span class="line">        skynet_callback(context, gL, forward_cb);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        skynet_callback(context, gL, _cb); <span class="comment">// 调用skynet_callback注册回调函数</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">int</span></span><br><span class="line">forward_cb(struct skynet_context * context, <span class="keyword">void</span> * ud, <span class="keyword">int</span> type, <span class="keyword">int</span> session, <span class="keyword">uint32_t</span> source, <span class="keyword">const</span> <span class="keyword">void</span> * msg, <span class="keyword">size_t</span> sz) &#123;</span><br><span class="line">    _cb(context, ud, type, session, source, msg, sz);</span><br><span class="line">    <span class="comment">// don't delete msg in forward mode.</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">int</span></span><br><span class="line">_cb(struct skynet_context * context, <span class="keyword">void</span> * ud, <span class="keyword">int</span> type, <span class="keyword">int</span> session, <span class="keyword">uint32_t</span> source, <span class="keyword">const</span> <span class="keyword">void</span> * msg, <span class="keyword">size_t</span> sz) &#123;</span><br><span class="line">    <span class="comment">// 太长略过，就是在这个snlua service的lua_State上执行逻辑啦</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// skynet_server.c</span></span><br><span class="line"><span class="keyword">void</span></span><br><span class="line">skynet_callback(struct skynet_context * context, <span class="keyword">void</span> *ud, skynet_cb cb) &#123;</span><br><span class="line">    context-&gt;cb = cb; <span class="comment">// 注册回调函数</span></span><br><span class="line">    context-&gt;cb_ud = ud;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>所以我们看到，最终处理消息的逻辑，就会注册到context的cb上。context会维护这个service专属的消息队列<code>message_queue</code>，多个service的消息队列在skynet里就被存放在一个全局唯一的队列<code>global_queue</code>中。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// skynet_mq.c</span></span><br><span class="line"><span class="comment">// 每个service的context的消息队列</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">message_queue</span> &#123;</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">spinlock</span> <span class="title">lock</span>;</span></span><br><span class="line">    <span class="keyword">uint32_t</span> handle; <span class="comment">// 也维护一个handle，通过这个handle，能反过来找到对应的context</span></span><br><span class="line">    <span class="keyword">int</span> cap;</span><br><span class="line">    <span class="keyword">int</span> head;</span><br><span class="line">    <span class="keyword">int</span> tail;</span><br><span class="line">    <span class="keyword">int</span> release;</span><br><span class="line">    <span class="keyword">int</span> in_global;</span><br><span class="line">    <span class="keyword">int</span> overload;</span><br><span class="line">    <span class="keyword">int</span> overload_threshold;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">skynet_message</span> *<span class="title">queue</span>;</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">message_queue</span> *<span class="title">next</span>;</span> <span class="comment">// 全局队列里的下一个</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 全局队列：双端message_queue队列</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">global_queue</span> &#123;</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">message_queue</span> *<span class="title">head</span>;</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">message_queue</span> *<span class="title">tail</span>;</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">spinlock</span> <span class="title">lock</span>;</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>在skynet架构启动之际，会根据用户配置创建全局消息队列以外，还会初始化定时器、日志、socket、集群等基础模块及服务。当然在这个过程中，也会创建几个worker：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// skynet_start.c</span></span><br><span class="line"><span class="keyword">void</span></span><br><span class="line">skynet_start(struct skynet_config * config) &#123;</span><br><span class="line">    <span class="comment">// 略过上面</span></span><br><span class="line">    skynet_mq_init();</span><br><span class="line">    <span class="comment">// 略过中间</span></span><br><span class="line">    start(config-&gt;thread); <span class="comment">// config中的thread配置项即为worker数</span></span><br><span class="line">    <span class="comment">// 略过下面</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">void</span></span><br><span class="line">start(<span class="keyword">int</span> thread) &#123;</span><br><span class="line">    <span class="comment">// 略过上面</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">int</span> weight[] = &#123;</span><br><span class="line">        <span class="number">-1</span>, <span class="number">-1</span>, <span class="number">-1</span>, <span class="number">-1</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>,</span><br><span class="line">        <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>,</span><br><span class="line">        <span class="number">2</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">2</span>,</span><br><span class="line">        <span class="number">3</span>, <span class="number">3</span>, <span class="number">3</span>, <span class="number">3</span>, <span class="number">3</span>, <span class="number">3</span>, <span class="number">3</span>, <span class="number">3</span>, &#125;; <span class="comment">// 每个worker的负载</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">worker_parm</span> <span class="title">wp</span>[<span class="title">thread</span>];</span></span><br><span class="line">    <span class="keyword">for</span> (i=<span class="number">0</span>;i&lt;thread;i++) &#123;</span><br><span class="line">        wp[i].m = m;</span><br><span class="line">        wp[i].id = i;</span><br><span class="line">        <span class="keyword">if</span> (i &lt; <span class="keyword">sizeof</span>(weight)/<span class="keyword">sizeof</span>(weight[<span class="number">0</span>])) &#123;</span><br><span class="line">            wp[i].weight= weight[i];</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            wp[i].weight = <span class="number">0</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        create_thread(&amp;pid[i+<span class="number">3</span>], thread_worker, &amp;wp[i]); <span class="comment">// 创建worker线程</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 略过下面</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// skynet_mq.c</span></span><br><span class="line"><span class="keyword">void</span></span><br><span class="line">skynet_mq_init() &#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">global_queue</span> *<span class="title">q</span> = <span class="title">skynet_malloc</span>(<span class="title">sizeof</span>(*<span class="title">q</span>));</span></span><br><span class="line">    <span class="built_in">memset</span>(q,<span class="number">0</span>,<span class="keyword">sizeof</span>(*q));</span><br><span class="line">    SPIN_INIT(q);</span><br><span class="line">    Q=q; <span class="comment">// 创建全局唯一global_queue</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>而这些worker会做什么呢？我们查看worker线程任务的函数定义即可知晓：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// skynet_start.c</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">void</span> *</span><br><span class="line">thread_worker(<span class="keyword">void</span> *p) &#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">worker_parm</span> *<span class="title">wp</span> = <span class="title">p</span>;</span></span><br><span class="line">    <span class="keyword">int</span> id = wp-&gt;id;</span><br><span class="line">    <span class="keyword">int</span> weight = wp-&gt;weight;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">monitor</span> *<span class="title">m</span> = <span class="title">wp</span>-&gt;<span class="title">m</span>;</span></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">skynet_monitor</span> *<span class="title">sm</span> = <span class="title">m</span>-&gt;<span class="title">m</span>[<span class="title">id</span>];</span></span><br><span class="line">    skynet_initthread(THREAD_WORKER);</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">message_queue</span> * <span class="title">q</span> = <span class="title">NULL</span>;</span></span><br><span class="line">    <span class="keyword">while</span> (!m-&gt;quit) &#123;</span><br><span class="line">        <span class="comment">// 当worker的监控monitor未退出时，循环运行，分发消息</span></span><br><span class="line">        q = skynet_context_message_dispatch(sm, q, weight);</span><br><span class="line">        <span class="comment">// 略过下面</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// skynet_server.c</span></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">message_queue</span> *</span></span><br><span class="line"><span class="class"><span class="title">skynet_context_message_dispatch</span>(<span class="title">struct</span> <span class="title">skynet_monitor</span> *<span class="title">sm</span>, <span class="title">struct</span> <span class="title">message_queue</span> *<span class="title">q</span>, <span class="title">int</span> <span class="title">weight</span>) &#123;</span></span><br><span class="line">    <span class="keyword">if</span> (q == <span class="literal">NULL</span>) &#123; <span class="comment">// 如果是一开始，或上一次预先取得消息队列为NULL</span></span><br><span class="line">        q = skynet_globalmq_pop(); <span class="comment">// 那么就尝试从全局队列中pop一个消息队列</span></span><br><span class="line">        <span class="keyword">if</span> (q==<span class="literal">NULL</span>)</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">uint32_t</span> handle = skynet_mq_handle(q);</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">skynet_context</span> * <span class="title">ctx</span> = <span class="title">skynet_handle_grab</span>(<span class="title">handle</span>);</span> <span class="comment">// 找到对应的context</span></span><br><span class="line">    <span class="keyword">if</span> (ctx == <span class="literal">NULL</span>) &#123;</span><br><span class="line">        <span class="class"><span class="keyword">struct</span> <span class="title">drop_t</span> <span class="title">d</span> = &#123;</span> handle &#125;;</span><br><span class="line">        skynet_mq_release(q, drop_message, &amp;d);</span><br><span class="line">        <span class="keyword">return</span> skynet_globalmq_pop(); <span class="comment">// 预先取下一个消息队列</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">int</span> i,n=<span class="number">1</span>;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">skynet_message</span> <span class="title">msg</span>;</span></span><br><span class="line">    <span class="keyword">for</span> (i=<span class="number">0</span>;i&lt;n;i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (skynet_mq_pop(q,&amp;msg)) &#123; <span class="comment">// 返回值为0表示消息队列不为空</span></span><br><span class="line">            skynet_context_release(ctx);</span><br><span class="line">            <span class="keyword">return</span> skynet_globalmq_pop();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (i==<span class="number">0</span> &amp;&amp; weight &gt;= <span class="number">0</span>) &#123;</span><br><span class="line">            n = skynet_mq_length(q);</span><br><span class="line">            n &gt;&gt;= weight;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">int</span> overload = skynet_mq_overload(q);</span><br><span class="line">        <span class="keyword">if</span> (overload) &#123;</span><br><span class="line">            skynet_error(ctx, <span class="string">"May overload, message queue length = %d"</span>, overload);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// skynet_monitor监控了每个worker，通过version标识分发消息的次数</span></span><br><span class="line">        <span class="comment">// 通过skynet_monitor_trigger，可以++version标识</span></span><br><span class="line">        <span class="comment">// worker是一直不断运行的。如果version一直没涨</span></span><br><span class="line">        <span class="comment">// 就说明某一个消息在分发处理时死循环了</span></span><br><span class="line">        skynet_monitor_trigger(sm, msg.source , handle);</span><br><span class="line">        <span class="keyword">if</span> (ctx-&gt;cb == <span class="literal">NULL</span>) &#123;</span><br><span class="line">            skynet_free(msg.data);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            dispatch_message(ctx, &amp;msg); <span class="comment">// 分发消息给对应的context</span></span><br><span class="line">        &#125;</span><br><span class="line">        skynet_monitor_trigger(sm, <span class="number">0</span>,<span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    assert(q == ctx-&gt;<span class="built_in">queue</span>);</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">message_queue</span> *<span class="title">nq</span> = <span class="title">skynet_globalmq_pop</span>();</span></span><br><span class="line">    <span class="keyword">if</span> (nq) &#123;</span><br><span class="line">        <span class="comment">// If global mq is not empty , push q back, and return next queue (nq)</span></span><br><span class="line">        <span class="comment">// Else (global mq is empty or block, don't push q back, and return q again (for next dispatch)</span></span><br><span class="line">        skynet_globalmq_push(q);</span><br><span class="line">        q = nq;</span><br><span class="line">    &#125;</span><br><span class="line">    skynet_context_release(ctx);</span><br><span class="line">    <span class="keyword">return</span> q;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">void</span></span><br><span class="line">dispatch_message(struct skynet_context *ctx, struct skynet_message *msg) &#123;</span><br><span class="line">    <span class="comment">// 略过前置检查逻辑</span></span><br><span class="line">    <span class="keyword">int</span> reserve_msg; <span class="comment">// 是否在内存中保留消息数据？</span></span><br><span class="line">    <span class="keyword">if</span> (ctx-&gt;profile) &#123; <span class="comment">// 如果在性能测试，记录cpu时间</span></span><br><span class="line">        ctx-&gt;cpu_start = skynet_thread_time();</span><br><span class="line">        reserve_msg = ctx-&gt;cb(ctx, ctx-&gt;cb_ud, type, msg-&gt;session, msg-&gt;source, msg-&gt;data, sz);</span><br><span class="line">        <span class="keyword">uint64_t</span> cost_time = skynet_thread_time() - ctx-&gt;cpu_start;</span><br><span class="line">        ctx-&gt;cpu_cost += cost_time;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 不管怎么样都要调用context的消息处理回调函数处理消息</span></span><br><span class="line">        reserve_msg = ctx-&gt;cb(ctx, ctx-&gt;cb_ud, type, msg-&gt;session, msg-&gt;source, msg-&gt;data, sz);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (!reserve_msg) &#123;</span><br><span class="line">        skynet_free(msg-&gt;data);</span><br><span class="line">    &#125;</span><br><span class="line">    CHECKCALLING_END(ctx)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>也就是说，这些worker会不断地从全局队列中取出单个消息队列，而后让这个消息队列所对应的service通过其context上注册的回调函数cb，处理相应的消息。</p>
<p>因此到这里，消息处理这一块的逻辑已经弄清了。如果要完成通信的闭环，还需要解决两个问题：</p>
<ul>
<li>发送方service如何推送消息到目标service？（<code>skynet.send</code>，非阻塞发送消息）</li>
<li>发送方如何获得目标service处理的返回值？（<code>skynet.call</code>，阻塞等待消息处理结果）</li>
</ul>
<p>我们先来看<code>skynet.send</code>。这个函数调用了底层注册的<code>send</code>函数，对应了<code>lua-skynet.c</code>中的<code>lsend</code>函数。我们以此为起点，观察消息推送的过程：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// lua-skynet.c</span></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">    uint32 address</span></span><br><span class="line"><span class="comment">     string address</span></span><br><span class="line"><span class="comment">    integer type</span></span><br><span class="line"><span class="comment">    integer session</span></span><br><span class="line"><span class="comment">    string message</span></span><br><span class="line"><span class="comment">     lightuserdata message_ptr</span></span><br><span class="line"><span class="comment">     integer len</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">int</span></span><br><span class="line">lsend(lua_State *L) &#123;</span><br><span class="line">    <span class="keyword">return</span> send_message(L, <span class="number">0</span>, <span class="number">2</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">int</span></span><br><span class="line">send_message(lua_State *L, <span class="keyword">int</span> source, <span class="keyword">int</span> idx_type) &#123;</span><br><span class="line">    <span class="comment">// 略过上面</span></span><br><span class="line">    <span class="comment">// 消息类型，一般在lua层写业务逻辑的话，都约定用string就好了</span></span><br><span class="line">    <span class="keyword">int</span> mtype = lua_type(L,idx_type+<span class="number">2</span>);</span><br><span class="line">    <span class="keyword">switch</span> (mtype) &#123;</span><br><span class="line">    <span class="keyword">case</span> LUA_TSTRING: &#123;</span><br><span class="line">        <span class="keyword">size_t</span> len = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">void</span> * msg = (<span class="keyword">void</span> *)lua_tolstring(L,idx_type+<span class="number">2</span>,&amp;len);</span><br><span class="line">        <span class="keyword">if</span> (len == <span class="number">0</span>) &#123;</span><br><span class="line">            msg = <span class="literal">NULL</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 我们可以指定某个服务的名称（string），或者地址（uint）</span></span><br><span class="line">        <span class="keyword">if</span> (dest_string) &#123;</span><br><span class="line">            <span class="comment">// 如果指定名称，走skynet_sendname逻辑，当然最后也会寻址，再去走skynet_send逻辑。</span></span><br><span class="line">            session = skynet_sendname(context, source, dest_string, type, session , msg, len);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            session = skynet_send(context, source, dest, type, session , msg, len);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 略过下面</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// skynet-server.c</span></span><br><span class="line"><span class="keyword">int</span></span><br><span class="line">skynet_send(struct skynet_context * context, <span class="keyword">uint32_t</span> source, <span class="keyword">uint32_t</span> destination , <span class="keyword">int</span> type, <span class="keyword">int</span> session, <span class="keyword">void</span> * data, <span class="keyword">size_t</span> sz) &#123;</span><br><span class="line">    <span class="comment">// 略过参数检验部分</span></span><br><span class="line">    <span class="keyword">if</span> (skynet_harbor_message_isremote(destination)) &#123;</span><br><span class="line">        <span class="comment">// 暂时略过harbor（集群）的部分</span></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        struct skynet_message smsg;  <span class="comment">// 把消息数据打包到skynet_message结构体</span></span><br><span class="line">        smsg.source = source;</span><br><span class="line">        smsg.session = session;</span><br><span class="line">        smsg.data = data;</span><br><span class="line">        smsg.sz = sz;</span><br><span class="line">        <span class="keyword">if</span> (skynet_context_push(destination, &amp;smsg)) &#123;  <span class="comment">// 推送到目标的context</span></span><br><span class="line">            skynet_free(data);</span><br><span class="line">            <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> session;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span></span><br><span class="line">skynet_context_push(<span class="keyword">uint32_t</span> handle, struct skynet_message *message) &#123;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">skynet_context</span> * <span class="title">ctx</span> = <span class="title">skynet_handle_grab</span>(<span class="title">handle</span>);</span></span><br><span class="line">    <span class="keyword">if</span> (ctx == <span class="literal">NULL</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    skynet_mq_push(ctx-&gt;<span class="built_in">queue</span>, message);  <span class="comment">// 把消息推入消息队列当中</span></span><br><span class="line">    skynet_context_release(ctx);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通过这样的一顿操作，就可以把消息发送到指定service的消息队列里了，然后就等worker来取消息回调处理啦~</p>
<p>那么第二个，如何实现获取处理结果的需求呢？这个是在lua层实现的，通过目标服务调用<code>skynet.ret</code>逻辑，<code>skynet.call</code>就可以获取返回值。我们来观察两边的逻辑：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- skynet.lua</span></span><br><span class="line"><span class="keyword">local</span> <span class="function"><span class="keyword">function</span> <span class="title">yield_call</span><span class="params">(service, session)</span></span></span><br><span class="line">    watching_session[session] = service <span class="comment">-- 监控是否有收到相应session的返回数据</span></span><br><span class="line">    session_id_coroutine[session] = running_thread</span><br><span class="line">    <span class="keyword">local</span> succ, msg, sz = coroutine_yield <span class="string">"SUSPEND"</span> <span class="comment">-- 挂起，直到该session有返回为止</span></span><br><span class="line">    watching_session[session] = <span class="literal">nil</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> succ <span class="keyword">then</span></span><br><span class="line">        <span class="built_in">error</span> <span class="string">"call failed"</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">return</span> msg,sz</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">skynet.call</span><span class="params">(addr, typename, ...)</span></span></span><br><span class="line">    <span class="keyword">local</span> tag = session_coroutine_tracetag[running_thread]</span><br><span class="line">    <span class="keyword">if</span> tag <span class="keyword">then</span></span><br><span class="line">        c.trace(tag, <span class="string">"call"</span>, <span class="number">2</span>)</span><br><span class="line">        c.send(addr, skynet.PTYPE_TRACE, <span class="number">0</span>, tag)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">local</span> p = proto[typename]</span><br><span class="line">    <span class="keyword">local</span> session = c.send(addr, p.id , <span class="literal">nil</span> , p.pack(...)) <span class="comment">-- 获取本次消息的session</span></span><br><span class="line">    <span class="keyword">if</span> session == <span class="literal">nil</span> <span class="keyword">then</span></span><br><span class="line">        <span class="built_in">error</span>(<span class="string">"call to invalid address "</span> .. skynet.address(addr))</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">return</span> p.<span class="built_in">unpack</span>(yield_call(addr, session))</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">skynet.ret</span><span class="params">(msg, sz)</span></span></span><br><span class="line">    <span class="comment">-- 在此逻辑之前，会通过dispatch_message分发消息，缓存消息的发送方、session等信息</span></span><br><span class="line">    msg = msg <span class="keyword">or</span> <span class="string">""</span></span><br><span class="line">    <span class="keyword">local</span> tag = session_coroutine_tracetag[running_thread]</span><br><span class="line">    <span class="keyword">if</span> tag <span class="keyword">then</span> c.trace(tag, <span class="string">"response"</span>) <span class="keyword">end</span></span><br><span class="line">    <span class="comment">-- 获取缓存的session信息</span></span><br><span class="line">    <span class="keyword">local</span> co_session = session_coroutine_id[running_thread]</span><br><span class="line">    session_coroutine_id[running_thread] = <span class="literal">nil</span></span><br><span class="line">    <span class="keyword">if</span> co_session == <span class="number">0</span> <span class="keyword">then</span></span><br><span class="line">        <span class="keyword">if</span> sz ~= <span class="literal">nil</span> <span class="keyword">then</span></span><br><span class="line">            c.trash(msg, sz)</span><br><span class="line">        <span class="keyword">end</span></span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span> <span class="comment">-- send don't need ret</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="comment">-- 获取缓存的发送方信息</span></span><br><span class="line">    <span class="keyword">local</span> co_address = session_coroutine_address[running_thread]</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> co_session <span class="keyword">then</span></span><br><span class="line">        <span class="built_in">error</span> <span class="string">"No session"</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="comment">-- 目标服务返回数据给发送方，带上session标识，表示这是该session消息的返回</span></span><br><span class="line">    <span class="keyword">local</span> ret = c.send(co_address, skynet.PTYPE_RESPONSE, co_session, msg, sz)</span><br><span class="line">    <span class="keyword">if</span> ret <span class="keyword">then</span></span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">    <span class="keyword">elseif</span> ret == <span class="literal">false</span> <span class="keyword">then</span></span><br><span class="line">        <span class="comment">-- If the package is too large, returns false. so we should report error back</span></span><br><span class="line">        c.send(co_address, skynet.PTYPE_ERROR, co_session, <span class="string">""</span>)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>
<p>可以看到，通过提供发送方与session标识信息，发送方就能够知道哪些消息是该session的返回值了。</p>
<p>这样一来，skynet内部的通信机制，就全部串上了！</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>一不小心写多了点，希望能有助于各位小伙伴加深对服务端以及skynet架构的理解。如果有叙述不当的地方，恳请指正~~~</p>
<p>那么skynet具体要怎么用呢？这一part暂时决定在后面的系列献上~</p>

      
    </div>

    

    
    
    

    
      
<div style="border: 1px solid black; margin-top: 32px; margin-bottom: 32px">
  <div style="margin-left:10px">
    <span style="font-weight:bold">版权声明</span>
    <br>
    <span>本文为博客<a href="https://utmhikari.github.io" style="color:#258FC6">HiKariのTechLab</a>原创文章，转载请标明出处，谢谢~~~</span>
  </div>
</div>


    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/源码分析/" rel="tag"># 源码分析</a>
          
            <a href="/tags/服务端/" rel="tag"># 服务端</a>
          
            <a href="/tags/lua/" rel="tag"># lua</a>
          
            <a href="/tags/skynet/" rel="tag"># skynet</a>
          
            <a href="/tags/lua-State/" rel="tag"># lua_State</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/10/08/easypython/pdf/" rel="next" title="【Easy Python】另类实用Python教程——Easy Python精编版上线">
                <i class="fa fa-chevron-left"></i> 【Easy Python】另类实用Python教程——Easy Python精编版上线
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/10/20/geekdaily/electron_react/" rel="prev" title="【极客日常】electron+react+antd深色主题打造桌面应用">
                【极客日常】electron+react+antd深色主题打造桌面应用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/avatar.png" alt="ひかり.HDQ">
            
              <p class="site-author-name" itemprop="name">ひかり.HDQ</p>
              <div class="site-description motion-element" itemprop="description">简约即走心</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">60</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">7</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">201</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL3V0bWhpa2FyaQ==" title="GitHub &rarr; https://github.com/utmhikari"><i class="fa fa-fw fa-github"></i>GitHub</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="bWFpbHRvOmhkcTk0MDYyM0AxMjYuY29t" title="Mail &rarr; mailto:hdq940623@126.com"><i class="fa fa-fw fa-envelope"></i>Mail</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly90ZXN0ZXJob21lLmNvbS91dG1oaWthcmk=" title="TesterHome &rarr; https://testerhome.com/utmhikari"><i class="fa fa-fw fa-tumblr"></i>TesterHome</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTM4NDI1MDE=" title="CSDN &rarr; https://blog.csdn.net/u013842501"><i class="fa fa-fw fa-copyright"></i>CSDN</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9zdGVhbWNvbW11bml0eS5jb20vaWQvdXRtaGlrYXJp" title="Steam &rarr; https://steamcommunity.com/id/utmhikari"><i class="fa fa-fw fa-steam"></i>Steam</span>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <span class="exturl" data-url="aHR0cHM6Ly9zcGFjZS5iaWxpYmlsaS5jb20vMTUwNzUxMTQv" title="Bilibili &rarr; https://space.bilibili.com/15075114/"><i class="fa fa-fw fa-bold"></i>Bilibili</span>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#skynet通信原理与源码分析"><span class="nav-number">2.</span> <span class="nav-text">skynet通信原理与源码分析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">3.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2019 – <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ひかり.HDQ</span>

  

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="post-meta-item-icon">
      <i class="fa fa-user"></i>
    </span>
    <span class="site-uv" title="总访客量">
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="post-meta-divider">|</span>
  

  
    <span class="post-meta-item-icon">
      <i class="fa fa-eye"></i>
    </span>
    <span class="site-pv" title="总访问量">
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>







  




















  
  <script src="//cdn.bootcss.com/jquery/2.1.3/jquery.min.js"></script>

  
  <script src="//cdn.bootcss.com/jquery_lazyload/1.9.7/jquery.lazyload.min.js"></script>

  
  <script src="//cdn.bootcss.com/velocity/1.2.1/velocity.min.js"></script>

  
  <script src="//cdn.bootcss.com/velocity/1.2.1/velocity.ui.min.js"></script>


  


  <script src="/js/src/utils.js?v=7.0.1"></script>

  <script src="/js/src/motion.js?v=7.0.1"></script>



  
  


  <script src="/js/src/affix.js?v=7.0.1"></script>

  <script src="/js/src/schemes/pisces.js?v=7.0.1"></script>




  
  <script src="/js/src/scrollspy.js?v=7.0.1"></script>
<script src="/js/src/post-details.js?v=7.0.1"></script>



  


  <script src="/js/src/next-boot.js?v=7.0.1"></script>


  

  
  <script src="/js/src/exturl.js?v=7.0.1"></script>


  

  


  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('5');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'manual') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
<script>
if ($('body').find('pre.mermaid').length) {
  $.ajax({
    type: 'GET',
    url: '//cdn.bootcss.com/mermaid/8.0.0-rc.8/mermaid.min.js',
    dataType: 'script',
    cache: true,
    success: function() {
      mermaid.initialize({
        theme: 'dark',
        logLevel: 3,
        flowchart: { curve: 'linear' },
        gantt: { axisFormat: '%m/%d/%Y' },
        sequence: { actorMargin: 50 }
      });
    }
  });
}
</script>


  
  <script>
    (function(){
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        }
        else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
  </script>


  

  

  

  

  

  
<script>
  $('.highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script>


  

  

</body>
</html>
